﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Provider;
using CE.PersonalAccident;

public partial class personal_accident_results : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[General.PAId] == null)
        {
            //Response.Redirect("personal-accident.aspx");
            //Response.Redirect("~/personal-accident/");
            BackToSearchPage();
        }

        if (Session[CE.Global.General.UserId] != null)
        {
            txtFullName.Text = Session[CE.Global.General.UserName].ToString();
            txtMobileNo.PhoneNo = Session[CE.Global.General.UserPhoneNo].ToString();
            txtEmail.Text = Session[CE.Global.General.UserEmail].ToString();

            txtFullName.ReadOnly = true;
            txtMobileNo.IsReadOnly = true;
            txtEmail.ReadOnly = true;
        }

        if (!IsPostBack)
        {
            Session[CE.Global.General.PAResultId] = null;
            if (Session[General.UserTypeId] != null)
            {
                if (Session[General.AgentId] == null && Session[General.UserTypeId].ToString() != "300")
                {
                    Session[CE.Global.General.ProviderCompanyId] = null;
                }
            }
            else if (Session[General.AgentId] == null)
            {
                Session[CE.Global.General.ProviderCompanyId] = null;
            }
            //ResultsQuotesDataBind();

            if (ViewState["SortOrder"] == null)
            {
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
            }

            if (ViewState["SortExpression"] == null)
            {
                ViewState["SortExpression"] = "";
                ViewState["SortExpression"] = "AnnualPremiumwithGST";
            }

            ResultsQuotesDataBind();
            LogUserViewedHistory();
        }
    }

    protected void ibtBack_Click(object sender, EventArgs e)
    {
        //Response.Redirect("personal-accident.aspx");
        //Response.Redirect("~/personal-accident/");

        BackToSearchPage();
    }

    protected void gvPAResult_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = cell.Controls[0] as LinkButton;
                    if (button != null)
                    {
                        Image imageSort = new Image();
                        imageSort.ImageUrl = "~/Images/icons/clear.gif";
                        HtmlGenericControl gv = new HtmlGenericControl("div");
                        Label lnkName = new Label();
                        lnkName.Text = button.Text;

                        if (ViewState["SortExpression"] != null && ViewState["SortExpression"].ToString() == button.CommandArgument.ToString())
                        {
                            if (ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() == SortDirection.Descending.ToString())
                            {
                                //imageSort.ImageUrl = "~/Images/icons/Sort_Down.gif";
                                imageSort.ImageUrl = "~/Images/icons/Sort_Down.gif";
                            }
                            else
                            {
                                //imageSort.ImageUrl = "~/Images/icons/Sort_Up.gif";
                                imageSort.ImageUrl = "~/Images/icons/Sort_Up.gif";
                            }
                        }

                        gv.Controls.Add(lnkName);
                        gv.Controls.Add(imageSort);
                        button.Controls.Add(gv);
                    }
                }
            }
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "javascript:orgBgColor = this.className; this.className = 'gridover';");
            e.Row.Attributes.Add("onmouseout", "javascript:this.className = orgBgColor;");

            controls_usrMoreInfoDropdownButton btnMoreInfo = (controls_usrMoreInfoDropdownButton)e.Row.FindControl("ibtMoreInfo");
            ImageButton btnApplyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");

            btnMoreInfo.RowId = "NewRow" + ((e.Row.RowIndex * 2) + 1).ToString();
            btnApplyNow.CommandArgument = e.Row.RowIndex.ToString();
        }
    }

    protected void gvPAResult_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("BuyNow"))
        {
            int index = Convert.ToInt32(e.CommandArgument);
            DataKey myData = gvPAResult.DataKeys[index];

            Int64 _resultId = Convert.ToInt64(myData[0].ToString());
            Int64 _companyId = Convert.ToInt64(myData[1].ToString());

            LogUserSelectHistory(_resultId, _companyId);
            Int64 _result = SavePremium(_resultId, _companyId);
            if (_result > 0)
            {
                Session[CE.Global.General.PAResultId] = myData[0].ToString();
                Session[CE.Global.General.ProviderCompanyId] = myData[1].ToString();
                if (_companyId == 23)
                {
                    Response.Redirect("~/personal-accident/proposalforms/hsbc_proposal_form.aspx");
                }
                else if (_companyId == 29)
                {
                    Response.Redirect("~/personal-accident/proposalforms/liberty_proposal_form.aspx");
                }
                else if (_companyId == 34)
                {
                    Response.Redirect("~/personal-accident/proposalforms/chinataiping_proposal_form.aspx");
                }
                else if (_companyId == 35)
                {
                    Response.Redirect("~/personal-accident/proposalforms/eq_proposal_form.aspx");
                }
                else if (_companyId == 30)
                {
                    Response.Redirect("~/personal-accident/proposalforms/etiqa_proposal_form.aspx");
                }
            }
        }
    }

    protected void gvPAResult_Sorting(object sender, GridViewSortEventArgs e)
    {
        SortGridViews(e.SortExpression);
    }

    protected void gvPAResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (Session[General.AgentId] != null)
        {
            e.Row.Cells[9].Visible = false;     //dental treatment
            e.Row.Cells[13].Visible = false;    //kidnap benefit
        }
        else
        {
            e.Row.Cells[6].Visible = false;     //temp total disablement
            e.Row.Cells[10].Visible = false;     //icu hospital
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //plan & product

            Label lblProductName = (Label)e.Row.FindControl("lblProductName");
            Label lblPlanName = (Label)e.Row.FindControl("lblPlanName");
            Image imgCompnayLogo = (Image)e.Row.FindControl("imgCompnayLogo");

            if (DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString() == "29")
            {
                lblProductName.Text = "PACare Plus";
                lblPlanName.Text = "Plan - " + DataBinder.Eval(e.Row.DataItem, "PlanName").ToString();
                imgCompnayLogo.ImageUrl = "~/images/public/logo/liberty.png";
            }
            else if (DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString() == "23")
            {
                lblProductName.Text = "AccidentSurance Plus";
                lblPlanName.Text = DataBinder.Eval(e.Row.DataItem, "PlanName").ToString();
                imgCompnayLogo.ImageUrl = "~/images/public/logo/hsbc.png";
            }
            else if (DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString() == "34")
            {
                lblProductName.Text = "Personal Accident Safe";
                lblPlanName.Text = DataBinder.Eval(e.Row.DataItem, "PlanName").ToString();
                imgCompnayLogo.ImageUrl = "~/images/public/logo/chartis.png";
            }
            else if (DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString() == "35")
            {
                lblProductName.Text = "EQ - PA";
                lblPlanName.Text = DataBinder.Eval(e.Row.DataItem, "PlanName").ToString();
                imgCompnayLogo.ImageUrl = "~/images/public/logo/eq.png";
            }
            else if (DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString() == "30")
            {
                lblProductName.Text = "e-Protect";
                lblPlanName.Text = DataBinder.Eval(e.Row.DataItem, "PlanName").ToString();
                imgCompnayLogo.ImageUrl = "~/images/public/logo/etiqa.png";
            }
            else if (DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString() == "24")
            {
                lblProductName.Text = "PA Protector";
                lblPlanName.Text = DataBinder.Eval(e.Row.DataItem, "PlanName").ToString();
                imgCompnayLogo.ImageUrl = "~/images/public/logo/rsa.png";
            }

            e.Row.Cells[4].Text = String.Format("{0:c0}", int.Parse(e.Row.Cells[4].Text));
            e.Row.Cells[5].Text = String.Format("{0:c0}", int.Parse(e.Row.Cells[5].Text));

            Label lblAnnualPremiumwithGST = (Label)e.Row.FindControl("lblAnnualPremiumwithGST");
            int _NoofChild = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "NoOfChild"));
            string _policyType = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "PolicyType"));
            string _WithGST = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "WithGST"));
            if (_policyType == "INDCHD" || _policyType == "INDSPCHD" && _NoofChild > 1)
            {
                float _apInd = Convert.ToSingle(DataBinder.Eval(e.Row.DataItem, "AnnualPremiumInd"));
                float _apSpo = Convert.ToSingle(DataBinder.Eval(e.Row.DataItem, "AnnualPremiumSpouse"));
                float _apChd = Convert.ToSingle(DataBinder.Eval(e.Row.DataItem, "AnnualPremiumChild"));
                float _calapChd = _apChd * _NoofChild;
                double TotalAP = (_apInd + _apSpo + _calapChd) + ((_apInd + _apSpo + _calapChd) * .07);
                lblAnnualPremiumwithGST.Text = "$" + TotalAP.ToString("#.00");
            }
            else
            {
                lblAnnualPremiumwithGST.Text = "$" + _WithGST.ToString();
            }

            string _providerid = DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString();
            //Check for Promo
            Int32 promodiscount = GetPromoDiscount(_providerid);

            if (promodiscount > 0)
            {
                if (_providerid == "30")
                {
                    lblAnnualPremiumwithGST.Text = "<font color=red>" + string.Format("{0:c}", Convert.ToSingle(_WithGST) - (Convert.ToSingle(_WithGST) / 10)) + "</font>";
                    lblAnnualPremiumwithGST.Text += " <s>" + string.Format("{0:c}", Convert.ToSingle(_WithGST)) + "</s> <br/>";
                    //lblAnnualPremiumwithGST.Text += " <s>" + string.Format("{0:c}", Convert.ToSingle(_WithGST) / (Convert.ToDouble(100 - promodiscount) / 100)) + "</s> <br/>";
                }
            }


            Label lblTempTotalDisable = (Label)e.Row.FindControl("lblTempTotalDisable");
            Image imgTempTotalDisable = (Image)e.Row.FindControl("imgTempTotalDisable");
            int _TempTotalTDPW = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "TempTDPW"));

            if (_TempTotalTDPW == 0)
            {
                imgTempTotalDisable.Visible = true;
                lblTempTotalDisable.Visible = false;
                lblTempTotalDisable.Text = "";
            }
            else
            {
                imgTempTotalDisable.Visible = false;
                lblTempTotalDisable.Visible = true;
                if (_TempTotalTDPW >= 1000)
                    lblTempTotalDisable.Text = _TempTotalTDPW.ToString("$#,000");
                else
                    lblTempTotalDisable.Text = _TempTotalTDPW.ToString("$#");
            }


            Label lblMedExpAdult = (Label)e.Row.FindControl("lblMedExpAdult");
            Image imgMedExpAdult = (Image)e.Row.FindControl("imgMedExpAdult");
            int _MedicalExpense = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "MedExpAdult"));

            if (_MedicalExpense == 0)
            {
                imgMedExpAdult.Visible = true;
                lblMedExpAdult.Visible = false;
                lblMedExpAdult.Text = "";
            }
            else
            {
                imgMedExpAdult.Visible = false;
                lblMedExpAdult.Visible = true;
                if (_MedicalExpense >= 1000)
                    lblMedExpAdult.Text = _MedicalExpense.ToString("$#,000");
                else
                    lblMedExpAdult.Text = _MedicalExpense.ToString("$#");
            }

            Label lblHCPDAdult = (Label)e.Row.FindControl("lblHCPDAdult");
            Image imgHCPDAdult = (Image)e.Row.FindControl("imgHCPDAdult");
            int _HCPDAdult = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "HCPDAdult"));

            if (_HCPDAdult == 0)
            {
                imgHCPDAdult.Visible = true;
                lblHCPDAdult.Visible = false;
                lblHCPDAdult.Text = "";
            }
            else
            {
                imgHCPDAdult.Visible = false;
                lblHCPDAdult.Visible = true;
                if (_HCPDAdult >= 1000)
                    lblHCPDAdult.Text = _HCPDAdult.ToString("$#,000");
                else
                    lblHCPDAdult.Text = _HCPDAdult.ToString("$#");
            }

            /*Sakthi On 13 Dec 2010
            Label lblRecupBenefit = (Label)e.Row.FindControl("lblRecupBenefit");
            Image imgRecupBenefit = (Image)e.Row.FindControl("imgRecupBenefit");
            int _RecupBenefit = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "RecupBenefit"));

            if (_RecupBenefit == 0)
            {
                imgRecupBenefit.Visible = true;
                lblRecupBenefit.Visible = false;
                lblRecupBenefit.Text = "";
            }
            else
            {
                imgRecupBenefit.Visible = false;
                lblRecupBenefit.Visible = true;
                if (_RecupBenefit >= 1000)
                    lblRecupBenefit.Text = _RecupBenefit.ToString("$#,000");
                else
                    lblRecupBenefit.Text = _RecupBenefit.ToString("$#");
            }

            Label lblBereaveRelief = (Label)e.Row.FindControl("lblBereaveRelief");
            Image imgBereaveRelief = (Image)e.Row.FindControl("imgBereaveRelief");
            int _BereaveRelief = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "BereaveRelief"));

            if (_BereaveRelief == 0)
            {
                imgBereaveRelief.Visible = true;
                lblBereaveRelief.Visible = false;
                lblBereaveRelief.Text = "";
            }
            else
            {
                imgBereaveRelief.Visible = false;
                lblBereaveRelief.Visible = true;
                if (_BereaveRelief >= 1000)
                    lblBereaveRelief.Text = _BereaveRelief.ToString("$#,000");
                else
                    lblBereaveRelief.Text = _BereaveRelief.ToString("$#");
            } */


            //Sakthi On 13 Dec 2010 -- Start 
            Label lblDentalTreatment = (Label)e.Row.FindControl("lblDentalTreatment");
            Image imgDentalTreatment = (Image)e.Row.FindControl("imgDentalTreatment");
            int _DentalTreatment = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "DentalTreatment"));

            if (_DentalTreatment == 0)
            {
                imgDentalTreatment.Visible = true;
                lblDentalTreatment.Visible = false;
                lblDentalTreatment.Text = "";
            }
            else
            {
                imgDentalTreatment.Visible = false;
                lblDentalTreatment.Visible = true;
                if (_DentalTreatment >= 1000)
                    lblDentalTreatment.Text = _DentalTreatment.ToString("$#,000");
                else
                    lblDentalTreatment.Text = _DentalTreatment.ToString("$#");
            }

            Label lblHospitalICU = (Label)e.Row.FindControl("lblHospitalICU");
            Image imgHospitalICU = (Image)e.Row.FindControl("imgHospitalICU");
            int _HospitalICU = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "HCPDAdult"));

            if (_HospitalICU == 0)
            {
                imgHospitalICU.Visible = true;
                lblHospitalICU.Visible = false;
                lblHospitalICU.Text = "";
            }
            else
            {
                imgHospitalICU.Visible = false;
                lblHospitalICU.Visible = true;
                if (_HospitalICU >= 1000)
                    lblHospitalICU.Text = _HospitalICU.ToString("$#,000");
                else
                    lblHospitalICU.Text = _HospitalICU.ToString("$#");
            }

            Label lblChineseMedicalExpenses = (Label)e.Row.FindControl("lblChineseMedicalExpenses");
            Image imgChineseMedicalExpenses = (Image)e.Row.FindControl("imgChineseMedicalExpenses");
            int _ChineseMedicalExpenses = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ChineseMedicalExpenses"));

            if (_ChineseMedicalExpenses == 0)
            {
                imgChineseMedicalExpenses.Visible = true;
                lblChineseMedicalExpenses.Visible = false;
                lblChineseMedicalExpenses.Text = "";
            }
            else
            {
                imgChineseMedicalExpenses.Visible = false;
                lblChineseMedicalExpenses.Visible = true;
                if (_ChineseMedicalExpenses >= 1000)
                    lblChineseMedicalExpenses.Text = _ChineseMedicalExpenses.ToString("$#,000");
                else
                    lblChineseMedicalExpenses.Text = _ChineseMedicalExpenses.ToString("$#");
            }

            Label lblCompassionateCash = (Label)e.Row.FindControl("lblCompassionateCash");
            Image imgCompassionateCash = (Image)e.Row.FindControl("imgCompassionateCash");
            int _CompassionateCash = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "CompassionateCash"));

            if (_CompassionateCash == 0)
            {
                imgCompassionateCash.Visible = true;
                lblCompassionateCash.Visible = false;
                lblCompassionateCash.Text = "";
            }
            else
            {
                imgCompassionateCash.Visible = false;
                lblCompassionateCash.Visible = true;
                if (_CompassionateCash >= 1000)
                    lblCompassionateCash.Text = _CompassionateCash.ToString("$#,000");
                else
                    lblCompassionateCash.Text = _CompassionateCash.ToString("$#");
            }

            Label lblKidnapBenefit = (Label)e.Row.FindControl("lblKidnapBenefit");
            Image imgKidnapBenefit = (Image)e.Row.FindControl("imgKidnapBenefit");
            int _KidnapBenefit = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "KidnapBenefit"));

            if (DataBinder.Eval(e.Row.DataItem, "isKidnapBenefit").ToString() == "True" && _KidnapBenefit == 0)
            {
                imgKidnapBenefit.Visible = true;
                imgKidnapBenefit.ImageUrl = "~/images/icons/tick.gif";
            }
            
            if (_KidnapBenefit == 0)
            {
                imgKidnapBenefit.Visible = true;
                lblKidnapBenefit.Visible = false;
                lblKidnapBenefit.Text = "";
            }
            else
            {
                imgKidnapBenefit.Visible = false;
                lblKidnapBenefit.Visible = true;
                if (_KidnapBenefit >= 1000)
                    lblKidnapBenefit.Text = _KidnapBenefit.ToString("$#,000");
                else
                    lblKidnapBenefit.Text = _KidnapBenefit.ToString("$#");
            }
            //Sakthi On 13 Dec 2010 -- End

            Label lblTempTDPW = new Label();
            Label lblTempPDPW = new Label();

            int _TempTDPW = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "TempTDPW"));
            if (_TempTDPW != 0)
            {
                if (_TempTDPW >= 1000)
                    lblTempTDPW.Text = _TempTDPW.ToString("$#,000");
                else
                    lblTempTDPW.Text = _TempTDPW.ToString("$#");
            }

            int _TempPDPW = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "TempPDPW"));
            if (_TempPDPW != 0)
            {
                if (_TempPDPW >= 1000)
                    lblTempPDPW.Text = _TempPDPW.ToString("$#,000");
                else
                    lblTempPDPW.Text = _TempPDPW.ToString("$#");
            }

            Label lblDeathPTD = new Label();
            Label lblLossOfTwoLimbs = new Label();
            Label lblLossofBothEyes = new Label();
            Label lblLossofBothEars = new Label();
            Label lblLossofSpeech = new Label();
            Label lblTotalParalysis = new Label();
            Label lblPermanentBedridden = new Label();
            Label lblLossof4FATRH = new Label();
            Label lblLossof4FATLH = new Label();
            Label lblLossof4FingerOH = new Label();
            Label lblLossofThumbBP = new Label();
            Label lblLossofThumbORP = new Label();
            Label lblLossofThumbOLP = new Label();
            Label lblLossofIF3P = new Label();
            Label lblLossofIF2P = new Label();
            Label lblLossofIF1P = new Label();
            Label lblLossofMF3P = new Label();
            Label lblLossofMF2P = new Label();
            Label lblLossofMF1P = new Label();
            Label lblLossofRF3P = new Label();
            Label lblLossofRF2P = new Label();
            Label lblLossofRF1P = new Label();
            Label lblLossofLF3P = new Label();
            Label lblLossofLF2P = new Label();
            Label lblLossofLF1P = new Label();
            Label lblLossofGT2P = new Label();
            Label lblLossofGT1P = new Label();
            Label lblLossofGT1orMoreP = new Label();
            Label lbl3DegreeBurn = new Label();

            Label lblPTDCash = new Label();
            Label lblTotalParalysisCash = new Label();
            Label lblLossofBothEyesCash = new Label();
            Label lblLossofSpeechCash = new Label();
            Label lblLossofBothEarsCash = new Label();
            Label lblLossofOneEyeOneLimbCash = new Label();
            Label lblLossofOneEarCash = new Label();
            Label lblLossofSEHKAWCash = new Label();
            Label lblLossofOneThumbCash = new Label();
            Label lblLossofOneForeFingerCash = new Label();
            Label lblLossofAnyOthFingerOneToeCash = new Label();
            Label lblLossofAnyOthToeCash = new Label();

            Int64 _PAId = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "PAID"));
            Int64 _PAInsId = Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, "PAInsId"));

            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();
            string _spName = "";
            if (Session[General.UserId] != null)
            {
                if (Session[General.UserTypeId].ToString() == "300")
                {
                    if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                        _spName = "sprocPAInsuranceRequestScaleSelectItemHSBC";
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                        _spName = "sprocPAInsuranceRequestScaleSelectItemLiberty";
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                        _spName = "sprocPAInsuranceRequestScaleSelectItemEtiqa";

                    //_spName = "sprocPAInsuranceRequestScaleSelectItemHSBC";
                }
                else
                {
                    _spName = "sprocPAInsuranceRequestScaleSelectItem";
                }
            }
            else
            {
                _spName = "sprocPAInsuranceRequestScaleSelectItem";
            }
            SortedList _sPara = new SortedList();
            _sPara.Add("@PAID", _PAId);
            _sPara.Add("@PAInsId", _PAInsId);
            _dtResult = _db.GetDataTableBySP(_spName, _sPara);
            if (_dtResult != null && _dtResult.Rows.Count > 0)
            {
                lblDeathPTD.Text = _dtResult.Rows[0]["DeathPerDisable"].ToString() + "%";
                lblLossOfTwoLimbs.Text = _dtResult.Rows[0]["LossTwoLimbs"].ToString() + "%";
                lblLossofBothEyes.Text = _dtResult.Rows[0]["LossBothEye"].ToString() + "%";
                lblLossofBothEars.Text = _dtResult.Rows[0]["LossBothEar"].ToString() + "%";
                lblLossofSpeech.Text = _dtResult.Rows[0]["LossSpeech"].ToString() + "%";
                lblTotalParalysis.Text = _dtResult.Rows[0]["TotParalysis"].ToString() + "%";
                lblPermanentBedridden.Text = _dtResult.Rows[0]["PerBedridden"].ToString() + "%";
                lblLossof4FATRH.Text = _dtResult.Rows[0]["LossFinRH"].ToString() + "%";
                lblLossof4FATLH.Text = _dtResult.Rows[0]["LossFinLH"].ToString() + "%";
                lblLossof4FingerOH.Text = _dtResult.Rows[0]["LossFinOneHand"].ToString() + "%";
                lblLossofThumbBP.Text = _dtResult.Rows[0]["LossThumbBothPhalanges"].ToString() + "%";
                lblLossofThumbORP.Text = _dtResult.Rows[0]["LossThumbRPhalanx"].ToString() + "%";
                lblLossofThumbOLP.Text = _dtResult.Rows[0]["LossThumbLPhalanx"].ToString() + "%";
                lblLossofIF3P.Text = _dtResult.Rows[0]["LossIndexFinThreePhalanges"].ToString() + "%";

                lblLossofIF2P.Text = _dtResult.Rows[0]["LossIndexFinTwoPhalanges"].ToString() + "%";
                lblLossofIF1P.Text = _dtResult.Rows[0]["LossIndexFinOnePhalanx"].ToString() + "%";
                lblLossofMF3P.Text = _dtResult.Rows[0]["LossMidFinThreePhalanges"].ToString() + "%";
                lblLossofMF2P.Text = _dtResult.Rows[0]["LossMidFinTwoPhalanges"].ToString() + "%";
                lblLossofMF1P.Text = _dtResult.Rows[0]["LossMidFinOnePhalanx"].ToString() + "%";
                lblLossofRF3P.Text = _dtResult.Rows[0]["LossRingFinThreePhalanges"].ToString() + "%";
                lblLossofRF2P.Text = _dtResult.Rows[0]["LossRingFinTwoPhalanges"].ToString() + "%";
                lblLossofRF1P.Text = _dtResult.Rows[0]["LossRingFinOnePhalanx"].ToString() + "%";
                lblLossofLF3P.Text = _dtResult.Rows[0]["LossLitFinThreePhalanges"].ToString() + "%";
                lblLossofLF2P.Text = _dtResult.Rows[0]["LossLitFinTwoPhalanges"].ToString() + "%";
                lblLossofLF1P.Text = _dtResult.Rows[0]["LossLitFinOnePhalanx"].ToString() + "%";
                lblLossofGT2P.Text = _dtResult.Rows[0]["LossGToeTwoPhalanges"].ToString() + "%";
                lblLossofGT1P.Text = _dtResult.Rows[0]["LossGToeOnePhalanx"].ToString() + "%";
                lblLossofGT1orMoreP.Text = _dtResult.Rows[0]["LossOToeOneMorePhalanges"].ToString() + "%";
                lbl3DegreeBurn.Text = GetPercentageorString(_dtResult.Rows[0]["ThirdDegreeBurn"].ToString());

                //For Etiqa
                Int32 _DeathPerDisable = Convert.ToInt32(_dtResult.Rows[0]["DeathPerDisable"].ToString());
                lblPTDCash.Text = String.Format("${0:0,0}", _DeathPerDisable);
                Int32 _TotParalysis = Convert.ToInt32(_dtResult.Rows[0]["TotParalysis"].ToString());
                lblTotalParalysisCash.Text = String.Format("${0:0,0}", _TotParalysis);
                Int32 _LossBothEye = Convert.ToInt32(_dtResult.Rows[0]["LossBothEye"].ToString());
                lblLossofBothEyesCash.Text = String.Format("${0:0,0}", _LossBothEye);
                Int32 _LossSpeech = Convert.ToInt32(_dtResult.Rows[0]["LossSpeech"].ToString());
                lblLossofSpeechCash.Text = String.Format("${0:0,0}", _LossSpeech);
                Int32 _LossBothEar = Convert.ToInt32(_dtResult.Rows[0]["LossBothEar"].ToString());
                lblLossofBothEarsCash.Text = String.Format("${0:0,0}", _LossBothEar);
                Int32 _LossOneEye = Convert.ToInt32(_dtResult.Rows[0]["LossOneEye"].ToString());
                lblLossofOneEyeOneLimbCash.Text = String.Format("${0:0,0}", _LossOneEye);
                Int32 _LossOneEar = Convert.ToInt32(_dtResult.Rows[0]["LossOneEar"].ToString());
                lblLossofOneEarCash.Text = String.Format("${0:0,0}", _LossOneEar);
                Int32 _PerBedridden = Convert.ToInt32(_dtResult.Rows[0]["PerBedridden"].ToString());
                lblLossofSEHKAWCash.Text = String.Format("${0:0,0}", _PerBedridden);
                Int32 _LossThumbBothPhalanges = Convert.ToInt32(_dtResult.Rows[0]["LossThumbBothPhalanges"].ToString());
                lblLossofOneThumbCash.Text = String.Format("${0:0,0}", _LossThumbBothPhalanges);
                Int32 _LossFinOneHand = Convert.ToInt32(_dtResult.Rows[0]["LossFinOneHand"].ToString());
                lblLossofOneForeFingerCash.Text = String.Format("${0:0,0}", _LossFinOneHand);
                Int32 _LossGToeOnePhalanx = Convert.ToInt32(_dtResult.Rows[0]["LossGToeOnePhalanx"].ToString());
                lblLossofAnyOthFingerOneToeCash.Text = String.Format("${0:0,0}", _LossGToeOnePhalanx);
                Int32 _LossOToeOneMorePhalanges = Convert.ToInt32(_dtResult.Rows[0]["LossOToeOneMorePhalanges"].ToString());
                lblLossofAnyOthToeCash.Text = String.Format("${0:0,0}", _LossOToeOneMorePhalanges);
            }

            string _insCompany = " Insurance";
            string _insComDescrip = "";
            //More Info Start
            controls_usrMoreInfoDropdownButton btnMoreInfo = (controls_usrMoreInfoDropdownButton)e.Row.FindControl("ibtMoreInfo");
            btnMoreInfo.RowId = "NewRow" + ((e.Row.RowIndex * 2) + 1).ToString();
            string _companyId = DataBinder.Eval(e.Row.DataItem, "PACompanyID").ToString();

            MyDatabase _dbProvider = new MyDatabase();
            DataTable _dtProviderResult = new DataTable();
            string _spName1 = "sprocProviderPromotionDescription";
            SortedList _sPara1 = new SortedList();
            _sPara1.Add("@ProviderCompanyId", _companyId);
            _dtProviderResult = _dbProvider.GetDataTableBySP(_spName1, _sPara1);
            if (_dtProviderResult != null && _dtProviderResult.Rows.Count > 0)
            {
                _insCompany = _dtProviderResult.Rows[0]["PromotionTitle"].ToString();
                _insComDescrip = _dtProviderResult.Rows[0]["PromotionDescription"].ToString();
            }

            HtmlTable dTable = new HtmlTable();

            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "http://" + myUri.Host;
            int _PACId = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "PACompanyID"));
            string _Policy = "";
            if (_PACId == 29)
            {
                _Policy = domainUrl + "/policy_docs/Liberty/PA/PACare_Plus_Policy_Details.pdf";
            }
            else if (_PACId == 23)
            {
                _Policy = domainUrl + "/policy_docs/HSBC/PA/accidentsurance.pdf";
            }
            else if (_PACId == 34)
            {
                _Policy = domainUrl + "/policy_docs/ChinaTaiping/PA/PersonalAccidentSafe.pdf";
            }
            else if (_PACId == 35)
            {
                _Policy = domainUrl + "/policy_docs/EQ/PA/eqpersonal_accident.pdf";
            }
            else if (_PACId == 30)
            {
                _Policy = domainUrl + "/policy_docs/Etiqa/PA/e-ProtectPAPolicy.pdf";
            }
            else if (_PACId == 24)
            {
                _Policy = domainUrl + "/policy_docs/RSA/PA/PersonalAccidentProtector.pdf";
            }


            string NavigateUrl = "javascript:HideRowMoreInfo(" + ((e.Row.RowIndex * 2) + 1).ToString() + ");";
            string _html = "<div id=\"framework_moreinfo\">"
                        + "<div id=\"container_moreinfo\">"
                        + "<div id=\"content_moreinfo\">"
                        + "<div id=\"tblwrap_moreinfo\">"
                        + "<div>"

                        + "<h1>" + _insCompany.ToString() + "</h1>"
                        + "<div id=\"viewbtn_mi\">"
                        + "<a target=\"_blank\" href=\"" + _Policy + "\"><img border-width: 0px; src=\"/images/button/view-policy.png\" /></a>"
                        + "</div>"
                        + "<p>" + _insComDescrip.ToString() + "<p/>"

                        + "</div>";
            if (_PACId != 30)
            {
                _html += "<h2>Disablement Scale</h2>"
                + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"

                + "<tr>"
                + "<th class=\"title_br\" width=\"35%\"></th>"
                + "<th align=\"center\" class=\"title_br\" width=\"15%\">Coverage</th>"
                + "<th class=\"title_br\" width=\"35%\"></th>"
                + "<th align=\"center\" width=\"15%\">Coverage</th>"
                + "</tr>";

                if (_TempTDPW != 0)
                {
                    _html += "<tr>"
                    + "<td class=\"ct_br_white\">Temporary Total Disablement (per week)</td>"
                    + "<td align=\"center\" class=\"ct_br_white\">" + lblTempTDPW.Text + "</td>";
                }
                else
                {
                    _html += "<tr>"
                    + "<td class=\"ct_br_white\">Temporary Total Disablement (per week)</td>"
                    + "<td align=\"center\" class=\"ct_br_white\"><img src=\"/images/icons/X.gif\" /></td>";
                }
                if (_TempPDPW != 0)
                {
                    _html += "<td class=\"ct_br_white\">Temporary Partial Disablement (per week)</td>"
                    + "<td align=\"center\" class=\"ct_br_white1\">" + lblTempPDPW.Text + "</td>"
                    + "</tr>";
                }
                else
                {
                    _html += "<td class=\"ct_br_white\">Temporary Partial Disablement (per week)</td>"
                    + "<td align=\"center\" class=\"ct_br_white1\"><img src=\"/images/icons/X.gif\" /></td>"
                    + "</tr>";
                }

                _html += "<tr>"
                + "<th class=\"title_br\" width=\"35%\">Other disabilities (Adult*/Child)</th>"
                + "<th align=\"center\" class=\"title_br\" width=\"15%\">Percentage</th>"
                + "<th class=\"title_br\" width=\"35%\">Other disabilities (Adult*/Child)</th>"
                + "<th align=\"center\" width=\"15%\">Percentage</th>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Death or Permanent Total Disability</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblDeathPTD.Text + "</td>"
                + "<td class=\"ct_br_white\">Loss of Index Finger(two phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofIF2P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">Loss of Two Limbs</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossOfTwoLimbs.Text + "</td>"
                + "<td class=\"ct_br_blue\">Loss of Index Finger(one phalanx)</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofIF1P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Loss of Sight in Both Eyes</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblLossofBothEyes.Text + "</td>"
                + "<td class=\"ct_br_white\">Loss of Middle Finger(three phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofMF3P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">Loss of Hearing in Both Ears</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossofBothEars.Text + "</td>"
                + "<td class=\"ct_br_blue\">Loss of Middle Finger(two phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofMF2P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Loss of Speech</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblLossofSpeech.Text + "</td>"
                + "<td class=\"ct_br_white\">Loss of Middle Finger(one phalanx)</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofMF1P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">Total Paralysis</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblTotalParalysis.Text + "</td>"
                + "<td class=\"ct_br_blue\">Loss of Ring Finger(three phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofRF3P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Permanent Bedridden</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblPermanentBedridden.Text + "</td>"
                + "<td class=\"ct_br_white\">Loss of Ring Finger(two phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofRF2P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">Loss of Four Fingers and Thumb of Right Hand</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossof4FATRH.Text + "</td>"
                + "<td class=\"ct_br_blue\">Loss of Ring Finger(one phalanx)</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofRF1P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Loss of Four Fingers and Thumb of Left Hand</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblLossof4FATLH.Text + "</td>"
                + "<td class=\"ct_br_white\">Loss of Little Finger(three phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofLF3P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">Loss of Four Fingers of One Hand</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossof4FingerOH.Text + "</td>"
                + "<td class=\"ct_br_blue\">Loss of Little Finger(two phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofLF2P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Loss of Thumb(both phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblLossofThumbBP.Text + "</td>"
                + "<td class=\"ct_br_white\">Loss of Little Finger(one phalanx)</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofLF1P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">Loss of Thumb(one right phalanx)</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossofThumbORP.Text + "</td>"
                + "<td class=\"ct_br_blue\">Loss of Great Toe(two phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofGT2P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Loss of Thumb(one left phalanx)</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblLossofThumbOLP.Text + "</td>"
                + "<td class=\"ct_br_white\">Loss of Great Toe(one phalanx)</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofGT1P.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">Loss of Index Finger(three phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossofIF3P.Text + "</td>"
                + "<td class=\"ct_br_blue\">Loss of Great Toe(one or more phalanges)</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofGT1orMoreP.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">3rd Degree Burns</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lbl3DegreeBurn.Text + "</td>"
                + "<td class=\"ct_br_white1\" colspan=\"2\">&nbsp;</td>"
                + "</tr>"

                + "</table>";
            }
            else if (_PACId == 30)
            {
                _html += "<h2>Table of Benefits</h2>"
               + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"

               + "<tr>"
               + "<th class=\"title_br\" width=\"35%\">Benefits</th>"
               + "<th align=\"center\" class=\"title_br\" width=\"15%\">Coverage</th>"
               + "<th class=\"title_br\" width=\"35%\">Benefits</th>"
               + "<th align=\"center\" width=\"15%\">Coverage</th>"
               + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">Permanent Total Disability</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblPTDCash.Text + "</td>"
                + "<td class=\"ct_br_white\">f) Permanent Total Loss of hearing in one ear.</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofOneEarCash.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">a) Permanent Total Paralysis or complete insanity or injuries resulting in being permanently bedridden.</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblTotalParalysisCash.Text + "</td>"
                + "<td class=\"ct_br_blue\">g) Permanent Total Loss of shoulder, elbow, hip, knee, ankle or wrist.</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofSEHKAWCash.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">b) Permanent Total Loss of sight of both eyes or use of both hands or both feet or combination of these.</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblLossofBothEyesCash.Text + "</td>"
                + "<td class=\"ct_br_white\">h) Permanent Total Loss of use or loss by amputation of:<br/> i) One thumb.</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofOneThumbCash.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">c) Permanent Total Loss of speech.</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossofSpeechCash.Text + "</td>"
                + "<td class=\"ct_br_blue\">ii) One forefinger.</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofOneForeFingerCash.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_white\">d) Permanent Total Loss of hearing on both ears.</td>"
                + "<td align=\"center\" class=\"ct_br_white\">" + lblLossofBothEarsCash.Text + "</td>"
                + "<td class=\"ct_br_white\">iii) Any other finger or one big toe.</td>"
                + "<td align=\"center\" class=\"ct_br_white1\">" + lblLossofAnyOthFingerOneToeCash.Text + "</td>"
                + "</tr>"

                + "<tr>"
                + "<td class=\"ct_br_blue\">e) Permanent Total Loss of sight of one eye or use of one limb.</td>"
                + "<td align=\"center\" class=\"ct_br_blue\">" + lblLossofOneEyeOneLimbCash.Text + "</td>"
                + "<td class=\"ct_br_blue\">iv) Any other toe.</td>"
                + "<td align=\"center\" class=\"ct_br_blue1\">" + lblLossofAnyOthToeCash.Text + "</td>"
                + "</tr>"

                + "</table>"

                + "<div> # includes Policy Owners’ Protection Scheme </div>";
            }
            _html += "</div>"
            + "</div>"
            + "</div>"
            + "<div id=\"footerMoreInfo2\">"
            + "<a href=\"" + NavigateUrl + "\"><img width=\"125;\" height=\"35;\" src=\"/images/moreinfo/nav/spacer.gif\" /></a>"
            + "</div>"
            + "</div>";


            btnMoreInfo.MoreInfo = _html.ToString().Replace("'", "\"");

            //buy now

            ImageButton ibtBuyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");

            //ibtBuyNow.OnClientClick = "javascript:void(0);ShowPopUp('" + _PAInsId.ToString() + "','" + _PACId.ToString() + "');return false;";
        }
    }

    private void LogUserSelectHistory(Int64 ResultId, Int64 CompanyId)
    {
        UserSelectHistoryDB _userselectdb = new UserSelectHistoryDB();
        _userselectdb.LogUserSelectHistory("PA", Request.Browser.Type, Request.UserHostAddress, "PA", ResultId, CompanyId);
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        //Sakthi on 15 Feb 2011 Command
        //_userviewdb.LogViewedHistory("PA", Request, "Personal Accident results.");
        _userviewdb.LogResultViewedHistory("PA", Request, "Personal Accident results.");
    }

    public string GetPercentageorString(string pert)
    {
        if (CE.Global.General.IsInteger(pert) == true)
        {
            if (Convert.ToInt32(pert.ToString()) > 0)
            {
                float val = Convert.ToInt32(pert.ToString());
                pert = Convert.ToString(val) + "%";
                return pert;
            }
            else if (Convert.ToInt32(pert.ToString()) == 0)
            {
                pert = "0%";
                return pert;
            }
            else
            {
                pert = pert + "%";
                return pert;
            }
        }
        else
        {
            return pert;
        }
    }

    public string GetImage(bool allowed)
    {

        if (allowed)

            return "~/images/icons/tick.gif";

        else

            return "~/images/icons/X.gif";

    }

    public string GetDoller(string Number)
    {
        Number = "$" + Number;
        return Number;
    }

    private void SortGridViews(string strExpression)
    {
        if (Cache["PAResultsQuotes" + Session[General.PAId].ToString()] == null)
        {
            GetTempResultTable();
        }

        if (ViewState["SortOrder"] == null)
        {
            ViewState["SortOrder"] = SortDirection.Descending;
        }

        if (ViewState["SortExpression"] == null)
        {
            ViewState["SortExpression"] = SortDirection.Ascending.ToString();
        }

        DataView dv = new DataView((DataTable)Cache["PAResultsQuotes" + Session[General.PAId].ToString()]);
        string strSort = "";
        //string strExpression = "";

        //if(e.SortExpression.ToString() != "InsurerName")
        //strExpression += e.SortExpression.ToString();

        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }
        else
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }
        string strSortExpress = "";
        //******************Begin To sort including InsurerName **********************************************
        //string[] arrExpress = strExpression.Split(',');

        //if (arrExpress.Length > 1)
        //{
        //    for (int i = 0; i < arrExpress.Length - 1; i++)
        //    {
        //        strSortExpress += arrExpress[i] + " " + strSort + ", ";
        //        if (arrExpress[i] == "InsurerName")
        //        {
        //            strSortExpress += "PlanOrder ASC, ";
        //        }
        //    }

        //}
        //strSortExpress += arrExpress[arrExpress.Length - 1] + strSort;
        //******************End To sort including InsurerName ***********************************************

        strSortExpress = strExpression + strSort;
        dv.Sort = strSortExpress;
        gvPAResult.DataSource = dv;
        gvPAResult.DataBind();
    }

    public string GetPolicyURl(string pacid)
    {
        string _url = "";
        string _policydoc = "";
        MyDatabase _db = new MyDatabase();
        string strTempSql = "SELECT UploadPath FROM tblProviderPolicyDoc where ProviderCompanyId =" + pacid + " AND ForWhat = 'PA'";
        if (_db.ExecuteScalarSqlStatement(strTempSql) == null)
        {
            _policydoc = null;
        }
        else
        {
            _policydoc = _db.ExecuteScalarSqlStatement(strTempSql).ToString();
        }
        if (_policydoc != null)
        {
            string docurl = _policydoc;

            HyperLink _lnkTest = new HyperLink();
            _lnkTest.NavigateUrl = docurl;
            _url = "javascript:window.open('" + _lnkTest.ResolveClientUrl(docurl) + "')";
        }
        return _url;
    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        DataView dv = new DataView((DataTable)Cache["PAResultsQuotes" + Session[General.PAId].ToString()]);
        dv.Sort = "AnnualPremiumwithGST ";
        gvPAResult.DataSource = dv;
        gvPAResult.DataBind();
    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        Int64 _paId = 0;
        string _spName = "";
        if (Session[General.UserId] != null)
        {
            //Response.Write("Agent ID : " + Session[General.AgentId].ToString());
            //Response.Write("Provider Company ID : " + Session[General.ProviderCompanyId].ToString());

            if (Session[General.UserTypeId].ToString() == "300")
            {
                if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListHSBC";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListLiberty";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("ChinaProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListChinaTaiping";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EQProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListEQ";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListEtiqa";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListRSA";
            }
            else if (Session[CE.Global.General.AgentId] != null &&
                 Session[CE.Global.General.ProviderCompanyId] != null)
            {

                if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListHSBC";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListLiberty";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("ChinaProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListChinaTaiping";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EQProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListEQ";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListEtiqa";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("RSAProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListRSA";
            }
            else
            {
                _spName = "sprocPAInsuranceRequestSelectItemList";
            }
        }
        else
        {
            if (Session[CE.Global.General.AgentId] != null &&
                 Session[CE.Global.General.ProviderCompanyId] != null)
            {
                if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListHSBC";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListLiberty";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("ChinaProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListChinaTaiping";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EQProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListEQ";
                else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("EtiqaProviderCompanyId"))
                    _spName = "sprocPAInsuranceRequestSelectItemListEtiqa";
            }
            else
            {
                _spName = "sprocPAInsuranceRequestSelectItemList";
            }
        }
        if (Session[CE.Global.General.PAId] != null)
        {
            _paId = Convert.ToInt64(Session[CE.Global.General.PAId].ToString());
        }
        SortedList _sPara = new SortedList();
        _sPara.Add("@PAID", _paId);

        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        Cache["PAResultsQuotes" + Session[General.PAId].ToString()] = _dtResult;
    }

    private void GetTempResultTable()
    {
        MyDatabase _db = new MyDatabase();
        string _strSP = "";
        SortedList _sPara = new SortedList();
        if (Session[CE.Global.General.PAId] != null)
        {
            _sPara.Add("@PAID", Session[CE.Global.General.PAId]);
            if (Session[General.UserId] != null)
            {
                if (Session[General.UserTypeId].ToString() == "300")
                {
                    if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("HSBCProviderCompanyId"))
                        _strSP = "sprocPAInsuranceRequestSelectItemListHSBC";
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("LibertyProviderCompanyId"))
                        _strSP = "sprocPAInsuranceRequestSelectItemListLiberty";
                }
                else
                {
                    _strSP = "sprocPAInsuranceRequestSelectItemList";
                }
            }
            else
            {
                _strSP = "sprocPAInsuranceRequestSelectItemList";
            }

            DataTable _dtResult = new DataTable();
            _dtResult = _db.GetDataTableBySP(_strSP, _sPara);
            Cache["PAResultsQuotes" + Session[General.PAId].ToString()] = _dtResult;
        }
        else
        {
            //Response.Redirect("personal-accident.aspx");
            
            BackToSearchPage();

        }
    }

    private void BackToSearchPage()
    {
        if (Request.QueryString["pid"] != null)
        {
            if (Request.QueryString["pid"].ToString() != "")
            {
                Response.Redirect("~/personal-accident/personal-accident.aspx?pid=" + Request.QueryString["pid"].ToString());
            }
            else
            {
                Response.Redirect("~/personal-accident/");
            }
        }
        else
        {
            Response.Redirect("~/personal-accident/");
        }
    }

    public void GetProviderDescription(Int64 ProviderCompanyId)
    {

    }

    public Int64 SavePremium(Int64 InsId, Int64 ProviderCompanyId)
    {
        Int64 _result = 0;
        double _AnnualPremium = 0;
        double _OrigPremium = 0;
        MyDatabase _db = new MyDatabase();
        string strSql = "";
        strSql = @"SELECT CAST(AnnualPremiumwithGST AS NUMERIC(10,2)) AS WithGST,* FROM tblProviderPACompareBenefits WHERE PAInsId = " + InsId;
        DataTable _dtResult = new DataTable();
        _dtResult = _db.GetDataTable(strSql);
        if (_dtResult.Rows.Count > 0)
        {
            MyDatabase _dbC = new MyDatabase();
            string strSqlC = "";
            int _NoofChild = 0;
            strSqlC = @"SELECT * FROM tblPAInsurance WHERE PAID = " + Session[General.PAId].ToString();
            DataTable _dtCResult = new DataTable();
            _dtCResult = _dbC.GetDataTable(strSqlC);
            if (_dtCResult.Rows.Count > 0)
            {
                _NoofChild = Convert.ToInt32(_dtCResult.Rows[0]["NoOfChild"].ToString());
            }
            string _WithGST = _dtResult.Rows[0]["WithGST"].ToString();

            if (_NoofChild > 1)
            {
                float _apInd = Convert.ToSingle(_dtResult.Rows[0]["AnnualPremiumInd"].ToString());
                float _apSpo = Convert.ToSingle(_dtResult.Rows[0]["AnnualPremiumSpouse"].ToString());
                float _apChd = Convert.ToSingle(_dtResult.Rows[0]["AnnualPremiumChild"].ToString()); ;
                float _calapChd = _apChd * _NoofChild;
                _AnnualPremium = (_apInd + _apSpo + _calapChd) + ((_apInd + _apSpo + _calapChd) * .07);
            }
            else
            {
                _AnnualPremium = Convert.ToSingle(_WithGST.ToString());
            }

            _OrigPremium = _AnnualPremium;
            //etiqa Promo
            Int32 promodiscount = GetPromoDiscount("30");

            if (promodiscount > 0)
            {
                if (ProviderCompanyId == 30)
                {
                    _AnnualPremium = _AnnualPremium - Convert.ToDouble(_AnnualPremium / promodiscount);
                }
            }

            PASelectItem _paselectitem = new PASelectItem();
            PASelectItemDB _paselectitemdb = new PASelectItemDB();

            _paselectitem.PASelectItemId = 0;
            _paselectitem.PAId = Convert.ToInt64(Session[General.PAId].ToString());
            _paselectitem.PAInsId = InsId;
            _paselectitem.ProviderCompanyId = ProviderCompanyId;
            _paselectitem.AnnualPremium = Convert.ToSingle(_AnnualPremium);
            if (Session[General.UserId] != null)
            {
                _paselectitem.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
            }
            else if (Session[CE.Global.General.PAPersonnelId] != null)
            {
                _paselectitem.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.PAPersonnelId].ToString());
            }
            else
            {
                _paselectitem.RefCEUserId = 0;
            }
            _paselectitem.Status = true;

            _result = _paselectitemdb.Insert(_paselectitem);

            if (promodiscount > 0)
            {
                //For Etiqa Promo
                PASelectItemPromo papromo = new PASelectItemPromo();
                PASelectItemPromoDB papromodb = new PASelectItemPromoDB();

                papromo.PASelectItemId = _result;
                papromo.PromotionID = GetEtiqaPromoID();
                papromo.AnnualPremium = Convert.ToSingle(_OrigPremium);
                papromo.DiscountedPremium = _paselectitem.AnnualPremium;
                papromo.RefCEUserId = _paselectitem.RefCEUserId;

                papromodb.Insert(papromo);
            }
        }
        return _result;
    }

    protected void btnBuyNow_Click(object sender, EventArgs e)
    {
        Int64 iPAID = 0;
        string Surname = "";
        string Mobile = "";
        string Email = "";

        if (Session[General.PAId] != null)
        {
            iPAID = Convert.ToInt64(Session[General.PAId].ToString());
        }
        else
        {
            iPAID = 0;
        }

        Surname = txtFullName.Text.ToUpper();
        Email = txtEmail.Text;
        Mobile = txtMobileNo.GetPhoneNo();
        
        PersonalAccidentDB _personalaccdb = new PersonalAccidentDB();
        Int64 _resultUpdate = _personalaccdb.UpdatePAContactInfo(iPAID, Surname, Mobile, Email);

        if (_resultUpdate > 0)
        {
            Int64 _resultId = Convert.ToInt64(inputPAInsID.Value.Trim());
            Int64 _companyId = Convert.ToInt64(inputPACompanyID.Value.Trim());

            LogUserSelectHistory(_resultId, _companyId);
            Int64 _result = SavePremium(_resultId, _companyId);
            if (_result > 0)
            {
                Session[CE.Global.General.PAResultId] = _resultId.ToString();
                Session[CE.Global.General.ProviderCompanyId] = _companyId.ToString();

                if (_companyId == 23)
                {
                    Response.Redirect("~/personal-accident/proposalforms/hsbc_proposal_form.aspx");
                }
                else if (_companyId == 29)
                {
                    Response.Redirect("~/personal-accident/proposalforms/liberty_proposal_form.aspx");
                }
                else if (_companyId == 34)
                {
                    Response.Redirect("~/personal-accident/proposalforms/chinataiping_proposal_form.aspx");
                }
                else if (_companyId == 35)
                {
                    Response.Redirect("~/personal-accident/proposalforms/eq_proposal_form.aspx");
                }
                else if (_companyId == 30)
                {
                    if (Request.QueryString["pid"] != null)
                    {
                        if (Request.QueryString["pid"].ToString() != "")
                        {
                            //Response.Redirect("~/personal-accident/personal-accident.aspx?pid=" + Request.QueryString["pid"].ToString());
                            Response.Redirect("~/personal-accident/proposalforms/etiqa_proposal_form.aspx?pid=" + Request.QueryString["pid"].ToString());
                        }
                        else
                        {
                            Response.Redirect("~/personal-accident/proposalforms/etiqa_proposal_form.aspx");
                        }
                    }
                    else
                    {
                        Response.Redirect("~/personal-accident/proposalforms/etiqa_proposal_form.aspx");
                    }
                    
                }
            }
        }
    }

    private Int32 GetPromoDiscount(string providerid)
    {
        Int32 Discount = 0;
        MyDatabase _db = new MyDatabase();
        string strSql = "SELECT ItemType FROM tblCXPromotion WHERE ProviderCompanyId = '" + providerid + "' and PromotionType = 500 and GETDATE() between StartDate and EndDate";
        DataTable _dt = new DataTable("aTable");
        _dt = _db.GetDataTable(strSql);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            Discount = Convert.ToInt32(_dt.Rows[0]["ItemType"].ToString());
        }

        return Discount;

    }

    private Int64 GetEtiqaPromoID()
    {
        Int64 PromoID = 0;
        MyDatabase _db = new MyDatabase();
        string strSql = "SELECT PromotionID FROM tblCXPromotion WHERE ProviderCompanyId = 30 and PromotionType = 500 and ItemType = 10 and GETDATE() between StartDate and EndDate";
        DataTable _dt = new DataTable("aTable");
        _dt = _db.GetDataTable(strSql);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            PromoID = Convert.ToInt64(_dt.Rows[0]["PromotionID"].ToString());
        }

        return PromoID;

    }

}
